import platform
from contextlib import contextmanager
from flask import Flask, jsonify, request, json, make_response
from selenium.webdriver.support.wait import WebDriverWait
import subprocess
from selenium.webdriver.support import expected_conditions as EC

app = Flask(__name__)
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import re
import requests
from wrapper import *
from v8_ops import *


def swtich_to(driver: webdriver.Chrome):
    handles = driver.window_handles
    for handle in handles:
        if handle != driver.current_window_handle:
            driver.close()
            driver.switch_to.window(handle)
            return driver
    return driver


def clean_res(res):
    response = make_response(res.replace(u'\xa0', u' ').replace(u'\xa9', u' ').replace(u'\xa5', u' '))
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


def ajax_complete(driver):
    return not driver.execute_script("return jQuery && jQuery.active")


@app.route('/', methods=['GET'])
def test():
    return '200'


@app.route('/', methods=['POST'])
def register():
    to = request.form['to']
    with keep_driver() as driver:
        driver.get(to)
        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")
        time.sleep(1)
        return clean_res(driver.page_source)


@app.route('/lagou', methods=['GET'])
def lagou():
    with keep_driver() as driver:
        driver.get("https://www.lagou.com/")
        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")
        if isElementExist(driver, '//*[@id="changeCityBox"]'):
            driver.find_element_by_xpath('//*[@id="changeCityBox"]/ul/li[7]/a').click()
        time.sleep(1)
        # no login
        if isElementExist(driver, '//*[@id="lg_tbar"]/div/ul/li[1]/a'):
            driver.find_element_by_xpath('//*[@id="lg_tbar"]/div/ul/li[1]/a').click()

            WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                     '/html/body/section/div[1]/div[2]/form/div[1]/input')) \
                .send_keys("15018465953")

            time.sleep(1)

            WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                     '/html/body/section/div[1]/div[2]/form/div[2]/input')) \
                .send_keys("a49810712a123")

            WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                     '/html/body/section/div[1]/div[2]/form/div[5]/input')) \
                .click()

        return clean_res(driver.page_source)


@app.route('/yiduopage', methods=['GET'])
def yiduopage():
    with new_driver() as driver:
        driver.get('https://www.cnyjzh.com/list.html')
        WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                 '//*[@id="pager"]/ul/li[13]')) \
            .click()
        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")
        return clean_res(driver.page_source)


@app.route('/bingchuan_next', methods=['GET'])
def bingchuan_next():
    with keep_driver() as driver:
        if len(driver.current_url) < 10:
            driver.get('https://cg.51bccf.com/finance_user/product_list.html?0#investHistory')
            return clean_res(driver.page_source)

        WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                 '//*[@id="next"]')) \
            .click()
        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")

        data = clean_res(driver.page_source)
        return data


@app.route('/bingchuan/<name>', methods=['GET'])
def bingchuan(name):
    with keep_driver() as driver:

        if name in ['1', '2', '3', '4', '5', '6', '7', '8']:
            WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                     '//*[@id="rptList-{}"]/a'.format(int(name) - 1))) \
                .click()
            data = clean_res(driver.page_source)
            driver.back()
            return data

        if len(driver.current_url) < 10:
            driver.get('https://cg.51bccf.com/finance_user/product_list.html?0#investHistory')
            return clean_res(driver.page_source)

        WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                 '//*[@id="next"]')) \
            .click()
        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")

        data = clean_res(driver.page_source)
        return data


@app.route('/yidaiyilu/<int:page>', methods=['GET'])
def yidaiyilu(page):
    with new_driver() as driver:
        driver.get('https://www.ydyilu.com/financing/sbtz/')

        WebDriverWait(driver, 10).until(ajax_complete, "Timeout waiting for page to load")
        WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                 '//*[@id="goPage"]')) \
            .send_keys(page)

        WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH,
                                                                 '//*[@id="pageContent"]/div/input[2]')) \
            .click()

        return clean_res(driver.page_source)


if __name__ == '__main__':
    import sys

    try:
        # app.run(threaded=True, debug=True, use_reloader=False)
        app.run(threaded=True, debug=True, use_reloader=True, port=5000)
    except Exception as e:
        print(e)
        sys.exit(0)
